package main

import (
	"elegantGo/chapter05/pkg/validate"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"net/http"
	"regexp"
)

func main() {

	validate.RegisterValidation("phone", func(fl validator.FieldLevel) bool {
		matched, _ := regexp.MatchString(`^(1[3-9][0-9]\d{8})$`, fl.Field().String())
		return matched
	})

	srv := gin.Default()
	srv.POST("/sms/send", func(c *gin.Context) {
		type SmsSend struct {
			Phone string `binding:"required,number,phone"`
		}
		req := new(SmsSend)
		if err := c.ShouldBind(req); err != nil {
			c.JSON(http.StatusOK, err.Error())
			return
		}
		c.JSON(http.StatusOK, req)
	})

	srv.POST("/user/sms/login", func(c *gin.Context) {
		type UserSmsLogin struct {
			Phone string `binding:"required,number,phone"`
			Code  string `binding:"required,number,len=4"`
		}

		req := new(UserSmsLogin)
		if err := c.ShouldBind(req); err != nil {
			c.JSON(http.StatusOK, err.Error())
			return
		}
		c.JSON(http.StatusOK, req)
	})

	srv.Run(":80")
}
